//priority_queue.h

#pragma once
#include<iostream>
#include<vector>
#include<functional>
using namespace std;

namespace My
{
    template <class T, class Container = vector<T>, class Compare = less<T> >
    class priority_queue
    {
    public:
        priority_queue()
        {}

        template <class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
        {
            while (first != last)
            {
                _c.push_back(*first);
                first++;
            }

            for (int i = (_c.size() - 2) / 2; i >= 0; i--)
            {
                adjust_down(i);
            }
        }

        void adjust_up(size_t child)
        {
            size_t parent = (child - 1) / 2;

            while (child > 0)
            {
                if (_comp(_c[parent], _c[child]))
                {
                    std::swap(_c[child], _c[parent]);
                    child = parent;
                    parent = (child - 1) / 2;
                }
                else
                {
                    break;
                }
            }
        }

        void adjust_down(size_t parent)
        {
            size_t child = parent * 2 + 1;

            while (child <_c.size())
            {
                if ( child + 1 < _c.size()&& _comp(_c[child], _c[child + 1]))
                {
                    child++;
                }
                if (_comp(_c[parent], _c[child]))
                {
                    std::swap(_c[child], _c[parent]);
                    parent = child;
                    child = parent * 2 + 1;
                }
                else
                {
                    break;
                }
            }
        }

        bool empty() const
        {
            return _c.empty();
        }

        size_t size() const
        {
            return _c.size();
        }
        const T& top() const
        {
            return _c[0];
        }
        void push(const T& x)
        {
            _c.push_back(x);
            adjust_up(_c.size() - 1);
        }
        void pop()
        {
            std::swap(_c[_c.size() - 1], _c[0]);
            _c.pop_back();
            adjust_down(0);
        }
    private:
        Container _c;
        Compare _comp;
    };

    void test01();
    void test02();

};